<template>
  <div class="upload-box">
    <el-upload
      action="#"
      :on-preview="handlePreview"
      :file-list="fileList"
      list-type="picture-card"
      :class="{disabled:fileComputed}"
      :http-request="handleRequest"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="srcImg" alt="" style="width=100%">
    </el-dialog>

  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDymLegRv96mBKCn68uObXCZfU9bleHdhU', // 身份识别ID
  SecretKey: 'XnlSs1sRjjSv71e05tQfdJiqgFWWFgqj' // 身份秘钥
})
export default {
  name: 'UpLoadImage',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      srcImg: ''
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length >= this.limit
    },
    uploadAllSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 查看图片 只有一个参数 预览
    handlePreview(file) {
      this.showDialog = true
      this.srcImg = file.url
    },
    // 图片上传之前的校验
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传的图片过大')
        return false
      }
    },
    // 覆盖默认上传图片方式
    handleRequest(obj) {
      const newObj = this.fileList.find(item => item.uid === obj.file.uid)
      cos.putObject({
        Bucket: 'hrsaas-1312861746', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: obj.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: obj.file, // 上传文件对象
        onProgress: (progressData) => {
          // 进度条
          newObj.status = 'uploading'
          newObj.percentage = Math.floor(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) return
        // 上传成功后的状态
        newObj.status = 'success'
        newObj.url = 'https://' + data.Location
      })
    },
    // 图片被删除时触发的钩子函数
    handleRemove(file, fileList) {
      this.fileList = [...fileList]
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
